import paho.mqtt.client
import time

# mqtt服务端，订阅topic
# 启动server，使用client发布消息，server接收client传递的数据(server端可以不放在服务器)
mqtt = paho.mqtt.client


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))  # 打印连接状态,rc=0连接成功
    client.subscribe("xgxx/v1/devices")  # 订阅 topic


def on_message(client, userdata, msg):
    print(msg.topic + " " + ":" + str(msg.payload))  # 打印接收的消息


client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
client = mqtt.Client(client_id)  # ClientId不能重复，所以使用当前时间
client.username_pw_set("mosquitto", "mosquitto")  # 必须设置，否则会返回「Connected with result code 4」
client.on_connect = on_connect
client.on_message = on_message
client.connect("10.90.18.140", 1883, 60)
client.loop_forever()
